<template>
	<div :class="containerClass">
		<div class="centered-content">
			<div class="title" v-show="platform=='windows'"><text>开发喵--喵了个喵</text></div>
			<div class="box1" v-for="(item, index) in items" :key="index">
				<div class="icon">
					<uni-icons custom-prefix="iconfont" :type="item.iconType"></uni-icons>
				</div>
				<div class="text">
					{{ item.description }}: <span>{{ item.remaining }}</span>
				</div>
			</div>
			<div class="paihangbang"><text @click="toRank">排行榜</text></div>
			<div class="paihangbang"><text @click="deleteInfo">退出登录</text></div>
			<p class="center" v-if="platform=='windows'">
				行:
				<select v-model="row" @change="generateImageGrid">
					<option :value="item" v-for="item in [3,6,9]">{{ item }}</option>
				</select>
				列:
				<select v-model="col" @change="generateImageGrid">
					<option :value="item" v-for="item in [3,6,9]">{{ item }}</option>
				</select>
			</p>
			<!-- 图表 -->
			<div class="center-container">
				<div :class="box2Class" :style="gridStyle">
					<div class="square" v-for="(item, index) in computedImageGrid" :key="index"
						:style="`${item.computedStyle}`" @click="showImageInBox3(item, index, $event)">
					</div>
				</div>
			</div>

			<div class="footer-container" v-show="platform=='windows'">
				<div class="row">
					<div class="box3" v-for="(image, index) in selectedImages" :key="index"
						:style="{ 'background-image': 'url(' + image + ')' }"></div>
				</div>
			</div>

			<div class="footer-container2" v-show="platform=='devtools'">
				<div class="row">
					<div class="box4" v-for="(image, index) in selectedImages" :key="index"
						:style="{ 'background-image': 'url(' + image + ')' }"></div>
				</div>
			</div>
		</div>
	</div>
</template>


<script>
	export default {
		data() {
			return {
				containerClass: 'container-mini-program',
				box2Class: 'box2-mini-program',
				platform: '',
				items: [{
						iconType: "icon-jinzita1",
						description: "剩余",
						remaining: ''
					},
					{
						iconType: "icon-yidongduantubiaoyuanwenjian-73",
						description: "用时",
						remaining: "00:00:00"
					},
					{
						iconType: "icon-jifen",
						description: "总分",
						remaining: 0
					}
				],
				row: 3,
				col: 3,
				images: [{
						url: "https://pic.imgdb.cn/item/64994b531ddac507cc039bfb.jpg",
						sort: '鸡腿'
					},
					{
						url: "https://pic.imgdb.cn/item/64994b4e1ddac507cc03959c.jpg",
						sort: '爆破果果'
					},
					{
						url: "https://pic.imgdb.cn/item/64994b481ddac507cc038cdd.png",
						sort: '汉堡包'
					},
					{
						url: "https://pic.imgdb.cn/item/64994b3d1ddac507cc037d92.jpg",
						sort: '大枣'
					},
					{
						url: "https://pic.imgdb.cn/item/64994b341ddac507cc036e31.jpg",
						sort: '蛋黄酥'
					},
					{
						url: "https://pic.imgdb.cn/item/64994b2a1ddac507cc03613a.jpg",
						sort: '手撕面包'
					},
					{
						url: "https://pic.imgdb.cn/item/64994b251ddac507cc0357f4.png",
						sort: '玉米'
					},
					{
						url: "https://pic.imgdb.cn/item/64994b181ddac507cc034924.jpg",
						sort: '夏威夷果'
					},
					{
						url: "https://pic.imgdb.cn/item/64994b0c1ddac507cc033296.png",
						sort: '芒果干'
					},
				],
				imageGrid: [],
				selectedImages: [],
				clickedCells: 0,
				totalCells: 0,
				seconds: 0,
				offsetXList: [],
				offsetYList: [],
			};
		},

		computed: {
			//对this.imageGrid数组中的每个元素进行遍历，
			//并返回一个新的数组，其中每个元素都包含原始元素的属性，并附加了一个computedStyle属性。
			computedImageGrid() {
				return this.imageGrid.map((item, index) => {
					
					const computedStyle = item.visible ?
						`background-image: url(${item.image}); transform: translate(${item.offsetX}px, ${item.offsetY}px);` :
						'visibility: hidden;';
					return {
						...item,
						computedStyle,
					};
				});
			},
			gridStyle() {
				const numRows = parseInt(this.row);
				const numCols = parseInt(this.col);
				const columnTemplate = `repeat(${numCols}, 1fr)`;
				const rowTemplate = `repeat(${numRows}, 1fr)`;
				return {
					gridTemplateColumns: columnTemplate,
					gridTemplateRows: rowTemplate,
				};
			}

		},
		mounted() {
			this.setPlatformSpecificClass(); //判断那个端的
			// 创建一个包含81个元素的数组
			this.generateImageGrid();
			// 进行偏移量的随机
			// this.generateRandomOffsets();
			this.getSession();
		},


		methods: {

			//判断端口
			setPlatformSpecificClass() {
				const platform = uni.getSystemInfoSync().platform;
				console.log(platform);
				if (platform === 'devtools') {
					this.containerClass = 'container-mini-program';
					this.box2Class = 'box2-mini-program'
					this.platform = 'devtools'
				} else if (platform === 'windows') {
					this.containerClass = 'container-web';
					this.box2Class = 'box2-web'
					this.platform = 'windows'
				}
			},
			getSession() {
				if (!uni.getStorageSync('userInfo')) {
					uni.showModal({
						title: '提示',
						content: '未登录请先登录！',
						success: res => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/login/login'
								});
							} else if (res.cancel) {
								uni.showToast({
									title: '登录才能继续！',
									icon: 'error'
								});
							}
						}
					});
				}
			},

			/**
			 * 核心：生成规定的格子数，并为每一个格子随机渲染图片
			 */
			generateImageGrid() {
				//初始化点击块个数
				this.clickedCells = 0;
				const numRows = parseInt(this.row); // 将行数解析为整数
				const numCols = parseInt(this.col); // 将列数解析为整数
				const totalCells = numRows * numCols; // 计算总格子数
				this.items[0].remaining = totalCells
				this.totalCells = totalCells;
				const numCategories = Math.min(this.images.length, numRows); // 确定要使用的图片类别数，取图片数和行数之间的较小值

				const shuffledImages = this.images.sort(() => 0.5 - Math.random()); // 随机打乱图片数组顺序
				const selectedImages = shuffledImages.slice(0, numCategories); // 根据类别数选择子集图片
				let imageIndex = 0; // 初始化图片索引

				this.imageGrid = Array.from({
						length: totalCells // 将数组长度设置为总格子数，不需要额外叠加层级
					},
					() => {
						// 创建长度为总格子数的数组
						const image = selectedImages[imageIndex]; // 获取当前索引处的图片
					 const offsetX =this.generateRandomOffsets();
					 const offsetY =this.generateRandomOffsets();
						imageIndex = (imageIndex + 1) % numCategories; // 更新图片索引，确保在类别数内循环
						return {
							image: image.url,
							sort: image.sort,
							visible: true,
							remaining: totalCells,
							offsetX,
							offsetY

						};
					}
				);

				for (let i = this.imageGrid.length - 1; i > 0; i--) {
					// 随机打乱 imageGrid 数组
					const j = Math.floor(Math.random() * (i + 1));
					[this.imageGrid[i], this.imageGrid[j]] = [this.imageGrid[j], this.imageGrid[i]];
					this.selectedImages = [];
				}
			},

			// 表格图片随机偏移量
			generateRandomOffsets() {
				
				return Math.floor(Math.random()*21)-10;
			},

			showImageInBox3(item, index) {
				if (uni.getStorageSync('userInfo')) {
					console.log(item, index);
					if (this.timerInterval === undefined) {
						this.startTimer();
					}
					this.selectedImages.push(item.image);
					this.$set(this.imageGrid[index], 'visible', false);
					//计算剩余小方格数量
					const remainingCount = this.imageGrid.filter(item => item.visible).length;
					this.items[0].remaining = remainingCount;
					this.clickedCells++; //点击数
					//回调函数接受两个参数：acc（accumulator）表示累积的结果，img表示当前迭代的数组元素
					const imageCounts = this.selectedImages.reduce((acc, img) => {
						console.log("acc", acc);
						console.log("img", img);
						acc[img] = (acc[img] || 0) + 1;
						return acc;
					}, {});
					// 用于存储要移除的图像
					let imageToRemove = null;
					// Object.entries方法来查找具有至少3个出现次数的图像。
					// 使用Object.entries方法将imageCounts对象转换为一个由键值对组成的数组。
					// 每个键值对是一个数组，其中第一个元素是键（即图像名称），第二个元素是对应的值（即图像出现的次数）。

					for (const [img, count] of Object.entries(imageCounts)) {
						if (count >= 3) {
							imageToRemove = img;
							break;
						}
					}

					if (imageToRemove) {
						this.selectedImages = this.selectedImages.filter(img => img !== imageToRemove);
						//，每消除一次总分+5
						this.items[2].remaining += 5;

					}
					if (this.clickedCells === this.totalCells) {
						// this.checkScore();
						// this.stopTimer();

						// 弹出"恭喜通关"的消息
						uni.showToast({
							title: '恭喜进入下一关！',
							icon: 'success',
							success: () => {
								this.row += 3; // 每通关一次行数增加3
								this.col += 3; // 每通关一次列数增加3
								if (this.row > 9 && this.col > 9) {
									uni.showToast({
										title: '恭喜通关！',
										icon: 'success',
										success: () => {
											this.checkScore();
											this.stopTimer();
										}
									});

								} else {
									this.generateImageGrid(); // 生成新的图像网格
								}
							}
						});

					}
					setTimeout(() => {
						if (this.selectedImages.length >= 7) {
							this.stopTimer()
							uni.showModal({
								title: '提示',
								content: '游戏结束是否重新开始？',
								success: res => {
									if (res.confirm) {
										uni.showToast({
											title: '游戏重新开始！',
											icon: 'success',
										});

										this.items[2].remaining = 0;
										this.selectedImages = [];
										this.timerInterval = undefined;
										this.generateImageGrid();
									} else if (res.cancel) {
										uni.showToast({
											title: '游戏未重新开始！',
											icon: 'error'
										});
									}
								}
							});

						}
					}, 1000)
				} else {
					return;
				}

			},
			totalScore() {
				var uid = parseInt(uni.getStorageSync(
						'userInfo')
					.uid)
				var score = parseInt(this.items[2].remaining)

				var card = parseInt(this.row * this.col)
				var cost = this.seconds
				var gametime = this.getCurrentDateTime();
				uni.request({
					url: 'http://localhost:3000/api/user/totalScore',
					method: 'POST',
					data: {
						uid: uid,
						score: score,
						card: card,
						cost: cost,
						gametime: gametime
					},

					success: (res) => {
						if (res.errMsg === 'request:ok') {
							uni.showToast({
								title: "您有新排名啦！",
							})
						} else {
							uni.showToast({
								title: "网络错误！",
							})
						}
					}
				});
			},

			updateScore() {
				var uid = parseInt(uni.getStorageSync(
					'userInfo').uid)
				var score = parseInt(this.items[2].remaining)
				var card = parseInt(this.row * this.col)
				var cost = this.seconds
				var gametime = this.getCurrentDateTime();
				uni.request({
					url: 'http://localhost:3000/api/user/updateScore',
					method: 'POST',
					data: {
						uid: uid,
						score: score,
						card: card,
						cost: cost,
						gametime: gametime
					},

					success: (res) => {
						console.log(res.errMsg);
						if (res.errMsg === 'request:ok') {
							uni.showToast({
								title: "您有新排名啦！",
							})
						} else {
							uni.showToast({
								title: "排名未更新",
							})
						}
					}
				});
			},
			checkScore() {
				var uid = parseInt(uni.getStorageSync(
						'userInfo')
					.uid)
				uni.request({
					url: 'http://localhost:3000/api/user/checkScore',
					method: 'GET',
					data: {
						uid: uid,
					},
					success: (res) => {
						console.log(JSON.stringify(res.data.code) + "bbb");
						if (res.data.code === 0) {
							this.updateScore();
						} else {
							this.totalScore();
						}
					}
				});
			},
			toRank() {
				uni.navigateTo({
					url: '/pages/ranking/ranking'
				});
			},

			deleteInfo() {
				uni.showModal({
					title: '提示',
					content: '确定退出登录吗',
					success: res => {
						if (res.confirm) {
							uni.clearStorage();
							uni.navigateTo({
								url: '/pages/login/login'
							});
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});

			},


			//开始计时
			startTimer() {
				let seconds = 0;
				this.timerInterval = setInterval(() => {
					seconds++;
					this.seconds = seconds;
					const formattedTime = this.formatTime(seconds);
					this.items[1].remaining = formattedTime;
				}, 1000);
			},
			//停止计时
			stopTimer() {
				clearInterval(this.timerInterval);
			},
			//格式化
			formatTime(seconds) {
				const hours = Math.floor(seconds / 3600);
				const minutes = Math.floor((seconds % 3600) / 60);
				const remainingSeconds = seconds % 60;
				const formattedHours = String(hours).padStart(2, '0');
				const formattedMinutes = String(minutes).padStart(2, '0');
				const formattedSeconds = String(remainingSeconds).padStart(2, '0');
				return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
			},
			getCurrentDateTime() {
				const now = new Date();

				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			}



		}
	};
</script>

<style>
	.container-web {
		width: 100%;
		height: 100vh;
		background-image: url("https://pic.imgdb.cn/item/64994b5f1ddac507cc03af21.jpg");
		background-size: cover;
		background-position: center;
	}

	.container-mini-program {
		width: 100%;
		height: 100vh;
		background-image: url("https://pic.imgdb.cn/item/649136bf1ddac507ccb8d31e.jpg");
		background-size: cover;
		background-position: center bottom 10px;
	}

	.centered-content {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.title {
		margin-top: 5px;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 30px;
	}

	.paihangbang {
		margin-top: 5px;
		margin-bottom: 5px;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 16px;
	}

	.box1 {
		height: 35px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.icon {
		width: 50px;
		height: 50px;
		margin: 0 10px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.text {
		width: 150px;
		height: 50px;
		margin: 0 10px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.center-container {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 30px;
	}

	.box2-web {
		width: auto;
		height: auto;
		/* background-color: rgba(0, 0, 0, 0.1); */
		display: grid;
	}

	.box2-mini-program {
		width: 90vw;
		height: 90vw;
		/* background-color: rgba(0, 0, 0, 0.1); */
		display: grid;
		grid-template-columns: repeat(9, 1fr);
		grid-template-rows: repeat(9, 1fr);
	}

	.square {
		width: 35.43px;
		height: 35.43px;
		background-color: #ffffff;
		border: 1px solid rgba(0, 0, 0, 0.2);
		/* background-size: cover; */
		/* background-size: 50%; */
		background-size: 30px 30px;
		background-position: center;
		background-repeat: no-repeat;
		margin: 2px;
		/* 添加上下左右边距为 5px */
	}

	.mask {
		width: 35.43px;
		height: 35.43px;
	}

	.mask.overlay {
		background-color: rgba(0, 0, 0, 0.5);
	}

	@media screen and (orientation: landscape) {
		.box2-web {
			width: auto;
			height: auto;
		}
	}

	@media screen and (orientation: landscape) {
		.box2-mini-program {
			width: auto;
			height: auto;
		}
	}

	.footer-container {
		position: absolute;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: rgba(0, 0, 0, 0.2);
		border: 1px solid rgba(0, 0, 0, 0.6);
		width: 50vh;
		height: 8vh;
		margin: 0 auto;
		padding: 10px;
		border-radius: 15px;
		bottom: 0;
		margin-bottom: 5px;
	}


	.row {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.box3 {
		width: 48px;
		height: 48px;
		background-color: #ffffff;
		border: 1px solid rgba(0, 0, 0, 0.2);
		/* 小方格的背景颜色 */
		margin: 0 2px;
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
	}

	.footer-container2 {
		position: absolute;
		display: flex;
		justify-content: center;
		align-items: center;
		bottom: 0;

	}

	.box4 {
		width: 45px;
		height: 45px;
		/* 小方格的背景颜色 */
		margin: 5px;
		margin-bottom: 51px;
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
	}
</style>